package com.start.common.tools;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class StartMapTools {
    /**
     * 获取map中指定key的值 如果key 不存在则创建这个key 并给指定键创建一个指定类型的集合
     *
     * @param map map对象
     * @param key 键
     * @param <T> 对象类型
     * @return
     */
    public static <T> List<T> getListByKey(Map map, Serializable key) {
        if (key == null) throw new RuntimeException("key is not null");
        if (map == null) throw new RuntimeException("map is not null");
        List<T> result;
        if (!map.containsKey(key)) {
            result = new ArrayList<>();
            map.put(key, result);
        }
        result = (List<T>) map.get(key);
        return result;
    }

    public static <T> void mapAddValue(Map map, Serializable key, T value) {
        if (key == null) throw new RuntimeException("key is not null");
        if (map == null) throw new RuntimeException("map is not null");
        if (value == null) throw new RuntimeException("value is not null");
        List<T> list = getListByKey(map, key);
        list.add(value);
    }

    public static <T> void mapAddList(Map map, Serializable key, List<T> value) {
        if (key == null) throw new RuntimeException("key is not null");
        if (map == null) throw new RuntimeException("map is not null");
        if (value == null) throw new RuntimeException("value is not null");
        List<T> list = getListByKey(map, key);
        list.addAll(value);
    }

    public static <T> void mapAddValue(Map map, T value, String keys, String keySplit) {
        if (StringUtils.isEmpty(keys) || StringUtils.isEmpty(keySplit) || !keys.contains(keySplit)) {
            StartMapTools.mapAddValue(map, keys, value);
            return;
        }
        String[] split = keys.split(keySplit);
        for (String key : split) {
            if (StringUtils.isEmpty(key)) {
                log.warn("value:" + value.getClass().getName() + " key contain Empty key");
                continue;
            }
            StartMapTools.mapAddValue(map, key, value);
        }
    }

    public static <T> void remove(Map map, T value, String keys, String keySplit) {
        if (map == null || map.isEmpty()) return;
        if (value == null) return;
        if (StringUtils.isEmpty(keys) || StringUtils.isEmpty(keySplit) || !keys.contains(keySplit)) {
            map.remove(keys);
            return;
        }

        String[] key = keys.split(keySplit);
        for (String k : key) {

        }
        if (StringUtils.isEmpty(keys) || StringUtils.isEmpty(keySplit) || !keys.contains(keySplit)) {
            StartMapTools.mapAddValue(map, keys, value);
            return;
        }
    }

    private static <T> void mapRemoveValue(List<T> list, T value) {
        list.remove(value);
    }

}
